import type { Directive, DirectiveBinding } from "vue";
interface ElType extends HTMLElement {
  __handleClick__: () => any;
  disabled: boolean;
}

const OFFSET = 100;
const DURATION = 500;

const map = new WeakMap();
const ob = new IntersectionObserver(entries => {
  for (const entry of entries) {
    if (entry.isIntersecting) {
      const animation = map.get(entry.target);
      if (animation) {
        animation.play();
        ob.unobserve(entry.target);
      }
    }
  }
});
const belowViewport = el => {
  const rect = el.getBoundingClientRect();
  return rect.top > window.innerHeight;
};
const slidein: Directive = {
  mounted(el: ElType, binding: DirectiveBinding) {
    if (!belowViewport(el)) {
      return;
    }
    // 实现上滑动画
    // 关键帧：@keyframes
    // 动画配置：animation
    const animation = el.animate(
      [
        {
          transform: `translateY(${OFFSET}px)`,
          opacity: 0.5
        },
        {
          transform: `translateY(0)`,
          opacity: 1
        }
      ],
      {
        duration: DURATION,
        easing: "ease-out",
        fill: "forwards"
      }
    );
    animation.pause();
    ob.observe(el);
    map.set(el, animation);
  },
  beforeUnmount(el: ElType) {
    ob.unobserve(el);
  }
};

export default slidein;
